<template>
  <div class="file-list-container">
    <!-- 查询条件 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="文件名">
        <el-input v-model="queryParams.filename" placeholder="请输入文件名" clearable />
      </el-form-item>
      <el-form-item label="上传用户">
        <el-input v-model="queryParams.uploaduser" placeholder="请输入上传用户" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 文件列表 -->
    <el-table :data="fileList" stripe style="width: 100%">
      <el-table-column prop="filename" label="文件名" />
      <el-table-column prop="filesize" label="文件大小" :formatter="formatFileSize" />
      <el-table-column prop="filetype" label="文件类型" />
      <el-table-column prop="uploadtime" label="上传时间" :formatter="formatDate" />
      <el-table-column prop="uploaduser" label="上传用户" />
      <el-table-column prop="filepath" label="路径" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="text" @click="handleView(scope.row)">查看</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="text" @click="handleDownload(scope.row)">下载文件</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      :current-page="queryParams.page"
      :page-size="queryParams.size"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <!-- 图片预览弹窗 -->
    <el-dialog v-model="dialogVisible" title="图片预览" width="80%">
      <el-image
        :src="currentImageUrl"
        fit="contain"
        style="width: 100%; height: 100%;"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios'; // 使用 axios 直接调用后端接口
import request from '../utils/request';

// 查询参数
const queryParams = ref({
  filename: '',
  uploaduser: '',
  page: 1,
  size: 10,
});

// 文件列表数据
const fileList = ref([]);

// 总条数
const total = ref(0);

// 图片预览弹窗控制
const dialogVisible = ref(false);

// 当前预览的图片 URL
const currentImageUrl = ref('');
 
const fileUrl = ref(''); // 上传后的文件地址

const errorMessage = ref(''); // 错误信息

// 获取文件列表
const fetchFileList = async () => {
  debugger;
  try {
    const response = await request.post('/file/queryFile', queryParams.value);
    fileList.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取文件列表失败');
  }
};

// 查询
const handleSearch = () => {
  queryParams.value.page = 1; // 重置页码
  fetchFileList();
};

// 重置查询条件
const resetQuery = () => {
  queryParams.value = {
    filename: '',
    uploaduser: '',
    page: 1,
    size: 10,
  };
  fetchFileList();
};

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.value.size = size;
  fetchFileList();
};

// 页码变化
const handlePageChange = (page) => {
  queryParams.value.page = page;
  fetchFileList();
};

// 格式化文件大小
const formatFileSize = (row) => {
  const size = row.filesize;
  if (size < 1024) {
    return `${size} B`;
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(2)} KB`;
  } else if (size < 1024 * 1024 * 1024) {
    return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  } else {
    return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
  }
};

// 格式化日期
const formatDate = (row) => {
  return new Date(row.uploadtime).toLocaleString();
};

// 查看文件详情
const handleView = (row) => {
  if (row.filetype.startsWith('image/')) {
    currentImageUrl.value = row.filepath; // 假设 row.fileurl 是图片的 URL
    dialogVisible.value = true; // 打开弹窗
  } else {
    ElMessage.warning('该文件不是图片，无法预览');
  }
};

// 删除文件
const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该文件吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        debugger;
        await request.post('/file/deleteFile',{id:row.id,filepath:row.storageid});
        ElMessage.success('删除成功');
        fetchFileList(); // 刷新列表
      } catch (error) {
        ElMessage.error('删除失败');
      }
    })
    .catch(() => {});
};

// 下载文件
const handleDownload = async (row) => {
debugger;
  try {
    const response = await request.post('/file/download', {
        fileUrl:row.filepath,
      responseType: 'blob', // 告诉服务器返回的是二进制数据
    });

    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    // 从文件 URL 中提取文件名，这里简单假设文件名在 URL 最后一部分
    const fileName = fileUrl.value.split('/').pop();
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success('文件下载成功！');
  } catch (error) {
    errorMessage.value = '文件下载失败：' + error.message;
    ElMessage.error('文件下载失败');
  }
};

// 初始化时加载数据
onMounted(() => {
  fetchFileList();
});
</script>

<style scoped>
.file-list-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>